<template>
  <div class="search-suggestion">
    <van-cell
      v-for="item in suggestions"
      :key="item"
      @click="$emit('search', item)"
      icon="search">
      <div slot="title" v-html="highlightText(item)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestion } from '@/api/search'
import { debounce } from 'lodash'

export default {
  name: 'search-suggestion',
  data () {
    return {
      suggestions: []
    }
  },
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  watch: {
    searchText: {
      handler: debounce(function (val) {
          this.loadSearchSuggestion(val)
      }, 200),
      immediate: true
    }
  },
  methods: {
    async loadSearchSuggestion () {
      try {
        const { data: { data: { options } } } = await getSearchSuggestion(this.searchText)

        this.suggestions = options
      } catch (err) {
        this.$toast('请求失败')
      }
    },
    highlightText (item) {
      let res = `<div>${item}</div>`

      const flag = new RegExp(this.searchText, 'ig')

      res = res.replace(flag, `<span class="active">${this.searchText}</span>`)

      return res
    }
  }
}
</script>

<style lang="less">
.active {
  color: red;
}
</style>

<style scoped lang="less">
</style>
